#include "cache.h"

Cache::Cache(QObject *parent) :
    QObject(parent), QHash()
{
}

void Cache::set(QString key, QList<QObject*> val)
{
    if(!objectsContainers.contains(key)) {
        QObject *container = new QObject();
        container->moveToThread(this->thread()); container->setParent(this);
        objectsContainers.insert(key,container);
    }

    QList<QObject*> old = get(key);
    for(int i=0; i<old.length(); i++) {
        if(old[i]->parent()==objectsContainers.value(key)) {
            delete old[i];
        }
    }

    for(int i=0; i<val.length(); i++) {
        val[i]->setParent(0);
        val[i]->moveToThread(this->thread());
        val[i]->setParent(objectsContainers.value(key));
    }

    QHash::insert(key, val);
}

void Cache::append(QString key, QObject* val) {
    if(!objectsContainers.contains(key)) {
        QObject *container = new QObject();
        container->moveToThread(this->thread()); container->setParent(this);
        objectsContainers.insert(key,container);
    }

    val->setParent(0);
    val->moveToThread(this->thread());
    val->setParent(objectsContainers.value(key));

    if(!QHash::contains(key)) {
        set(key,QList<QObject*>());
    }

    QList<QObject*> list = this->get(key);
    list.append(val);

    QHash::insert(key,list);
}

QList<QObject*> Cache::get(QString key)
{
    return QHash::value(key);
}

void Cache::clear()
{
    qDeleteAll(objectsContainers);
    objectsContainers.clear();

    QHash::clear();
}
